package com.css.dzj.zfjg.modules.clue.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.aq.server.service.BaseService;
import com.css.dzj.zfjg.common.util.BeanUtil;
import com.css.dzj.zfjg.common.util.Constant;
import com.css.dzj.zfjg.common.util.R;
import com.css.dzj.zfjg.common.util.export.ExcelData;
import com.css.dzj.zfjg.common.util.export.ExportExcelUtils;
import com.css.dzj.zfjg.common.util.expot.ExcelUtil;
import com.css.dzj.zfjg.modules.clue.entity.Clue;
import com.css.dzj.zfjg.modules.clue.service.ClueService;
import com.css.dzj.zfjg.modules.detail.entity.Detail;
import com.css.dzj.zfjg.modules.detail.service.DetailService;
import com.querydsl.core.QueryResults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 信用线索企业详情controller
 */
@RestController
@RequestMapping("/clue")
public class ClueController {

    @Autowired
    private ClueService clueService;

    @Autowired
    private DetailService detailService;

    @Autowired
    private BaseService baseService;


    /**
     * 添加信用线索企业详情
     * @param clue
     * @return
     */
    @PostMapping("/add")
    public R addClue(@RequestBody Clue clue, HttpServletRequest request) {
        try {
            if(StringUtils.isEmpty(clue)) {
                return R.error("信用线索企业详情不能为空");
            }
            if(StringUtils.isEmpty(clue.getEnterpriseName()) || StringUtils.isEmpty(clue.getEnterpriseIdNumber()) || StringUtils.isEmpty(clue.getEnterpriseIdType()) ||
                   StringUtils.isEmpty(clue.getCreditClueReasons())) {
                return R.error("必填字段不能为空");
            }
            clueService.add(clue, request);
            baseService.logSuccess(3, "添加企业信用线索成功", "2");
            return R.ok();
        } catch(Exception e) {
            e.printStackTrace();
            baseService.logSuccess(3, "添加企业信用线索失败", "2");
            return R.error(e.getMessage());
        }

    }


    /**
     * 更新企业线索信用详情
     * @param clue
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody Clue clue) {
        try {
            if(StringUtils.isEmpty(clue)) {
                return R.error("信用线索企业详情不能为空");
            }
            Clue oldClue = clueService.findById(clue.getId());
            BeanUtil.copyBeanNotEmptyToBean(clue, oldClue);
            clue.setUpdateTime(new Date());
            clueService.update(clue);
            baseService.logSuccess(3, "修改企业信用线索成功", "2");
            return R.ok();
        } catch(Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "修改企业信用线索失败","2");
            return R.error(e.getMessage());
        }
    }

    /**
     * 通过id查询信用线索企业详情
     * @param id
     * @return
     */
    @GetMapping("/queryById")
    public R queryById(@RequestParam String id) {
        try {
            Clue clue = clueService.findById(id);
            baseService.logSuccess(3, "查看企业信用线索详情成功", "2");
            return R.ok().put("data", clue);
        } catch(Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "查看企业信用线索详情失败", "2");
            return R.error(e.getMessage());
        }
    }

    /**
     * 查询所有信用线索企业详情
     * @param pageSize
     * @param pageNo
     * @return
     */
    @GetMapping("/queryAll")
    public R queryAll(@RequestParam Integer pageSize, @RequestParam Integer pageNo) {
        try {
            PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
            QueryResults<Clue> clueQueryResults = clueService.queryAll(pageRequest);
            baseService.logSuccess(3, "查询所有企业信用线索成功", "2");
            return R.ok().put("data", clueQueryResults);
        } catch(Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "查询所有企业信用线索失败", "2");
            return R.error(e.getMessage());
        }
    }


    /**
     * 多条件分页查询信用线索企业详情
     * @param pageSize
     * @param pageNo
     * @param enterpriseName
     * @param creditClueReasons
     * @param enterpriseIdNumber
     * @param status
     * @return
     */
    @GetMapping("listClue")
    public R listClue(@RequestParam Integer pageSize, @RequestParam Integer pageNo,
                      @RequestParam String enterpriseName, @RequestParam String creditClueReasons,
                      @RequestParam String enterpriseIdNumber, @RequestParam String status) {
        try {
            PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
            QueryResults<Clue> clueQueryResults = clueService.listClue(pageRequest, enterpriseName, enterpriseIdNumber, creditClueReasons, status);
            baseService.logSuccess(3, "分页查询企业信用线索成功", "2");
            return R.ok().put("data", clueQueryResults);
        } catch(Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "分页查询企业信用线索失败", "2");
            return R.error(e.getMessage());
        }
    }

    /**
     * 通过企业证件号码查询企业信用线索
     * @param enterpriseIdNumber
     * @return
     */
    @GetMapping("/queryByIdNumber")
    public R queryByIdNumber(@RequestParam String enterpriseIdNumber) {
        try {
            Clue clue = clueService.queryByIdNumber(enterpriseIdNumber);
            Boolean isClue = false; // 判断该企业是否有企业信用线索
            if(clue != null) {
                isClue = true;
            }
            //baseService.logSuccess(3, "通过企业证件号码查询企业信用线索成功", "2");
            return R.ok().put("data", clue).put("isClue", isClue);
        } catch(Exception e) {
            e.printStackTrace();
            //baseService.logFailed(3, "通过企业证件号码查询企业信用线索失败", "2");
            return R.error(e.getMessage());
        }
    }

    @GetMapping("/delete")
    public R delete(@RequestParam String id) {
        try {
            if(StringUtils.isEmpty(id)) {
                return R.error("信用线索id不能为空");
            }
            Clue clue = clueService.findById(id);
            if(StringUtils.isEmpty(clue)) {
                return R.error("企业信用线索不能为空");
            }
            clueService.delete(clue);
            baseService.logSuccess(3, "删除企业信用线索成功", "2");
            return R.ok();
        } catch(Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "删除企业信用线索失败", "2");
            return R.error(e.getMessage());
        }
    }


    /**
     * 从Excel表格中批量导入数据到数据库
     * 信用线索详情批量导入
     *
     * @param file
     * @athor liyuan
     * @return
     */
    @PostMapping("/import")
    public R addClueFromExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            clueService.addClueFromExcel(file, request);
            baseService.logSuccess(3, "导入企业信用线索成功", "2");
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "导入企业信用线索失败", "2");
            return R.error(e.getMessage());
        }
    }

    /**
     *导出信用线索详情
     */
    @GetMapping(value = "/exportClue")
    public void exportClue(HttpServletResponse response,
                            @RequestParam(required = false) String enterpriseName,
                            @RequestParam String enterpriseIdNumber,
                            @RequestParam String creditClueReasons,
                            @RequestParam String status){

        PageRequest pageRequest = PageRequest.of(0, 2000);
        //获取数据
        QueryResults<Clue> clu = clueService.listClue(pageRequest, enterpriseName, enterpriseIdNumber, creditClueReasons, status);
        List<Clue> cluList = clu.getResults();

        if( cluList!=null || cluList.size()>=0 ){
            //创建导出实体
            ExcelData data = new ExcelData();
            data.setName("企业信用线索表");
            List<String> titles = new ArrayList();
            titles.add("序号");
            titles.add("企业名称");
            titles.add("企业证件类型");
            titles.add("企业证件号码");
            titles.add("信用线索原因");
            titles.add("评估日期");
            titles.add("信用线索评估状态");
            data.setTitles(titles);

            List<List<Object>> rows = new ArrayList();
            for (int i = 0; i < cluList.size(); i++) {
                List<Object> row = new ArrayList();
                row.add(String.valueOf(i+1));
                row.add(cluList.get(i).getEnterpriseName());
                row.add(cluList.get(i).getEnterpriseIdType());
                row.add(cluList.get(i).getEnterpriseIdNumber());
                if("A".equals(cluList.get(i).getCreditClueReasons())){
                    row.add("A");
                }else if("B".equals(cluList.get(i).getCreditClueReasons())){
                    row.add("B");
                }else if("C".equals(cluList.get(i).getCreditClueReasons())){
                    row.add("C");
                }else if("D".equals(cluList.get(i).getCreditClueReasons())){
                    row.add("D");
                }else if("E".equals(cluList.get(i).getCreditClueReasons())){
                    row.add("E");
                }else {
                    row.add(cluList.get(i).getCreditClueReasons());
                }
                SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
                String formaTime = spf.format(cluList.get(i).getEvaluationDate());
                row.add(formaTime);
                if("0".equals(cluList.get(i).getStatus())){
                    row.add("已接收");
                }else if("1".equals(cluList.get(i).getStatus())){
                    row.add("已调整");
                }else if("2".equals(cluList.get(i).getStatus())){
                    row.add("已反馈");
                }else {
                    row.add(cluList.get(i).getStatus());
                }
                rows.add(row);
            }
            data.setRows(rows);
            try {
                ExportExcelUtils.exportExcel(response,"企业信用线索表.xlsx",data);
                baseService.logFailed(3, "导出企业信用线索成功", "2");
            }catch (Exception e){
                baseService.logFailed(3, "导出企业信用线索失败", "2");
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     *导出信用线索详情
     */
    @RequestMapping("/exportExcel")
    @SuppressWarnings("uncheckd")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response){
        List headList = new ArrayList();
        List<String[]> dataList = new ArrayList<String[]>();
        String title = "企业信用线索表";
        String headStr= "序号,企业名称,企业证件类型,企业证件号码,信用线索原因,评估日期,信用线索评估状态";

        String[] strArr = headStr.split(",");
        headList = Arrays.asList(strArr);
        List<Map> nounList = clueService.getAll();

        for(int i=0;i<nounList.size();i++){
            Map map = (Map)nounList.get(i);
            String[] caseRecordArr = new String[strArr.length];
            for(int j=0;j<headStr.split(",").length;j++){
                caseRecordArr[j] = map.get(strArr[j]) == null?"":map.get(strArr[j]).toString();
            }
            caseRecordArr[0] = String.valueOf(i+1);
            dataList.add(caseRecordArr);
        }
        System.out.println(dataList);
        try {
            ExcelUtil.createExcel(response,title, headList, dataList);
            baseService.logSuccess(3, "导出企业信用线索成功", "2");
        } catch (Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "导出企业信用线索失败", "2");
        }
    }


    /**
     *接收安平系统传来的实体，分别加入到信用信息表和信用线索表
     * @author wt
     * @date 2020\3\11 0011
     */
    @PostMapping("/enterprisevo")
    public R enterprise( @RequestBody String enterpriseVO) {

        System.out.println(enterpriseVO);
        Object JSONObject = JSON.parseObject(enterpriseVO);
        try {
            if(StringUtils.isEmpty(enterpriseVO)){
                baseService.logFailed(3, "操作失败", "2");
                return R.error("参数为空");
            }
            SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
            //企业信用线索表
            Clue clue = clueService.queryByIdNumber((String)((JSONObject) JSONObject).get("enterpriseIdNumber"));
            if(!StringUtils.isEmpty(clue)){
                clue.setEnterpriseName((String)((JSONObject) JSONObject).get("enterpriseName"));
                clue.setEnterpriseIdType((String)((JSONObject) JSONObject).get("enterpriseIdType"));
                clue.setCreditClueReasons((String)((JSONObject) JSONObject).get("creditClueReasons"));
                clue.setNegativeDetails((String)((JSONObject) JSONObject).get("negativeDetails"));
                clue.setProvincial((String)((JSONObject) JSONObject).get("provincial"));
                clue.setMunicipalLevel((String)((JSONObject) JSONObject).get("municipalLevel"));
                clue.setCountyLevel((String)((JSONObject) JSONObject).get("countyLevel"));
                clue.setNationalStandard1Name((String)((JSONObject) JSONObject).get("nationalStandard1Name"));
                clue.setNationalStandard2Name((String)((JSONObject) JSONObject).get("nationalStandard2Name"));
                clue.setNationalStandard3Name((String)((JSONObject) JSONObject).get("nationalStandard3Name"));
                clue.setNationalStandard4Name((String)((JSONObject) JSONObject).get("nationalStandard4Name"));
                clue.setEvaluationDate((Date) ((JSONObject) JSONObject).get("evaluationDate"));
                String evaDateStr = (String)((JSONObject) JSONObject).get("evaluationDate");
                System.out.println(evaDateStr);
                if(!StringUtils.isEmpty(evaDateStr)) {
                    Date evaluationDate = spf.parse(evaDateStr);
                    if(evaluationDate != null) {
                        clue.setEvaluationDate(evaluationDate);
                    }
                }

                clue.setStatus(Constant.ADJUSTED);
                clue.setUpdateTime(new Date());
                clueService.update(clue);
            }

            //企业信用信息表
            Detail detail = detailService.queryByIdNumber((String)((JSONObject) JSONObject).get("enterpriseIdNumber"));
            if(!StringUtils.isEmpty(detail)){
                detail.setEnterpriseName((String)((JSONObject) JSONObject).get("enterpriseName"));
                detail.setEnterpriseScoreNumber((String)((JSONObject) JSONObject).get("enterpriseScoreNumber"));
                detail.setEnterpriseIdType((String)((JSONObject) JSONObject).get("enterpriseIdType"));
                detail.setEnterpriseScore((String)((JSONObject) JSONObject).get("enterpriseScore"));
                detail.setEnterpriseClassification((String)((JSONObject) JSONObject).get("enterpriseClassification"));
                //detail.setAssessmentDate((Date) ((JSONObject) JSONObject).get("assessmentDate"));
                String assDateStr = (String)((JSONObject) JSONObject).get("assessmentDate");
                if(!StringUtils.isEmpty(assDateStr)) {
                    Date assessmentDate = spf.parse(assDateStr);
                    if(assessmentDate != null) {
                        detail.setAssessmentDate(assessmentDate);
                    }
                }
                detail.setStatus(Constant.ADJUSTED);
                detail.setUpdateTime(new Date());
                detailService.update(detail);
            }

            if(StringUtils.isEmpty(clue) && StringUtils.isEmpty(detail)){

                baseService.logFailed(3, "企业信用和信息线索没有变化", "2");
                return R.ok("企业信用和信息线索没有变化");
            }
            baseService.logSuccess(3, "操作成功", "2");
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            baseService.logFailed(3, "操作失败", "2");
            return R.error(e.getMessage());
        }
    }

}
